package utils

import (
	"fmt"
	"image"
	"image/jpeg"
	_ "image/jpeg"
	_ "image/png"
	"io"

	"os"
	"path/filepath"
	"strings"
)

func filePath(path string) string {
	// 根目录
	var stRootDir string

	// 路径分隔符
	var stSeparator string

	//拿到分隔符
	stSeparator = string(filepath.Separator)
	//取到当前文件的绝对路径,返回一个字符串
	stWorkDir, _ := os.Getwd()

	//LastIndex返回目标字符串在指定字符传最后出现的位置
	stRootDir = stWorkDir[:strings.LastIndex(stWorkDir, stSeparator)]

	return fmt.Sprintf("%s/%s", stRootDir, path)
}
func ImgCompress(imgItem io.Reader, fileName string) {

	//file, err := os.OpenFile(filePath("static/img/91767193_p0.png"), os.O_RDONLY, 777)
	//if err != nil {
	//	fmt.Println(err.Error())
	//	return
	//}
	//file2 := bufio.NewWriter(imgItem)
	img, _, err := image.Decode(imgItem)
	// 创建输出文件
	out, err := os.Create("./static/img/" + fileName)
	if err != nil {
		panic(err)
	}
	defer out.Close()

	// 将图像转换为PNG格式并写入文件
	err = jpeg.Encode(out, img, &jpeg.Options{Quality: 50})
	if err != nil {
		panic(err)
	}
	//强制刷新写出文件
	//err = file2.Flush()
	if err != nil {
		return
	}
}
